mod java_process;
mod rand_str;

use tauri::Manager;
use tauri::path::BaseDirectory;
use std::time::Duration;
use std::thread;
use crate::java_process::JavaProcess;
// 新增：路径解析辅助函数
fn resolve_resource_path(app: &tauri::AppHandle, relative_path: &str) -> Result<String, tauri::Error> {
    let path = app
        .path()
        .resolve(relative_path, BaseDirectory::Resource)?
        .to_string_lossy()
        .into_owned()
        .trim_start_matches(r"\\?\")
        .to_string();
    Ok(path)
}

// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .setup(|app| {
            // 调用辅助函数获取路径
            let jar_path = resolve_resource_path(&app.handle(), "back/backend-1.0.0-SNAPSHOT.jar")?;
            let java_path = resolve_resource_path(&app.handle(), "back/jre-custom/bin/javaw.exe")?;

            let java_process = JavaProcess::new(
                java_path.clone(), // Jar 包路径
                jar_path.clone(), // Java 可执行文件路径
                Some(app.handle().clone()) // 传递 AppHandle 而非 &mut App
            );
            println!("jar path: {:?}\njava path: {:?}", jar_path, java_path);
            java_process.start().expect("启动失败");
            
            // 关键修改：将 java_process 存入 Tauri 应用状态（全局可访问）
            app.manage(java_process);
            Ok(())
        })
        .on_window_event(|window, event|{
            match event {
                tauri::WindowEvent::CloseRequested { .. } => {
                    // 从应用状态中获取 JavaProcess 实例
                    let app_handle = window.app_handle();
                    let java_process = app_handle.state::<JavaProcess>();
                    // 调用 stop 方法（需要处理 Result）
                    if let Err(e) = java_process.stop() {
                        eprintln!("关闭 Java 进程失败: {}", e);
                    }
                    thread::sleep(Duration::from_secs(1));
                }
                _ => {}
            }
        })
        .plugin(tauri_plugin_opener::init())
        .invoke_handler(tauri::generate_handler![greet])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}